import time
import os
import cv2
import base64
from flask import Flask, render_template
from flask_socketio import SocketIO, emit
import threading

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app)

camera_streams = {}

camera = None

F = False


def capture_video(camera_id):
    global F
    global camera
    print('capture_video: ', camera_id)

    camera = cv2.VideoCapture(camera_id)
    camera.set(cv2.CAP_PROP_FRAME_WIDTH, 640)  # 降低分辨率
    camera.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)  # 降低分辨率
    camera.set(cv2.CAP_PROP_FPS, 15)  # 降低帧率

    while True:
        if F:
            break

        success, frame = camera.read()  # 捕获视频帧

        if success:

            # frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
            # 将帧编码为JPEG格式
            _, buffer = cv2.imencode('.jpg', frame)
            frame_data = buffer.tobytes()

            # 将帧数据转换为base64编码以便通过WebSocket传输
            frame_encoded = base64.b64encode(frame_data).decode('utf-8')

            # kzeng add
            camera_streams[camera_id] = frame_encoded
            # 推送帧数据到前端
            socketio.emit('video_frame', {'frame': frame_encoded})

        socketio.sleep(0.001)  # 控制推送频率以减少资源消耗
    F = False


# 打开摄像头
@socketio.on('start_camera')
def start_camera(data):
    camera_id = int(data['camera_id'])
    print(f"打开摄像头 {camera_id}")
    capture_video(camera_id)


# 关闭摄像头
@socketio.on('stop_camera')
def stop_camera(data):
    print('***************stop camera*************************')
    global F
    global camera
    F = True
    camera.release()
    camera = None
    emit('stop_camera', {'status': 'ok'})

    #camera_id = int(data['camera_id'])
    #cap = cv2.VideoCapture(camera_id)
    #if not cap.isOpened():
    #    pass
    #else:
    #    print('---------------Stop camera------------------')
    #    F = True # 跳出来
    #    cap.release()


@socketio.on('get_camera_index_list')
def get_camera_index_list(data):
    cam_idx_lst = []
    for i in range(30):
        cap = cv2.VideoCapture(i)
        if cap.isOpened():
            print('------------------------------------')
            print(f"Camera ID: {i}")
            print(f"Frame width: {cap.get(cv2.CAP_PROP_FRAME_WIDTH)}")
            print(f"Frame height: {cap.get(cv2.CAP_PROP_FRAME_HEIGHT)}")
            print(f"FPS: {cap.get(cv2.CAP_PROP_FPS)}")
            print()
            cam_idx_lst.append(i)
            cap.release()

    socketio.emit('camera_index_list', {'cam_idx_lst': cam_idx_lst})


# 拍照并保存图片
@socketio.on('take_picture')
def take_picture(data):
    filename = None
    ret = True
    camera_id = int(data['camera_id'])

    if camera_id in camera_streams:
        print("camera_id in camera_streams")

        frame_encoded = camera_streams[camera_id]
        # print("-----frame-----")
        # print(frame_encoded)

        if True:
            timestamp = time.strftime("%Y-%m-%d_%H-%M-%S", time.localtime())
            filename = os.path.join('static/photo_camera', f'camera_{camera_id}_{timestamp}.bmp')

            # 将 base64 编码的帧数据解码并保存为 BMP 图片
            with open(filename, "wb") as f:
                f.write(base64.b64decode(frame_encoded))
            print(f"Frame saved at {filename}")
    else:
        print(f"Error: Camera ID {camera_id} not found in camera_streams")
        ret = False

    if not ret:
        emit('picture_taken', {'status': 'error'})
    else:
        emit('picture_taken', {'status': 'ok', 'image_url': filename})


@app.route('/')
def index():
    return render_template('index.html')


if __name__ == '__main__':
    socketio.run(app, debug=True, use_reloader=False,port=5166)
